package pl.edu.pb.wi.cookbook.controller;

import java.util.Arrays;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import pl.edu.pb.wi.cookbook.entity.Cookbook;
import pl.edu.pb.wi.cookbook.service.CookbookService;
import pl.edu.pb.wi.cookbook.session.UserSession;

@Controller
@RequestMapping("/cookbook")
public class CookbookController {
    private static final Logger log = Logger.getLogger(CookbookController.class
            .getName());
    private CookbookService cookbookService;
    private UserSession userSession;

    @Autowired
    public CookbookController(CookbookService cookbookService,
            UserSession userSession) {
        this.cookbookService = cookbookService;
        this.userSession = userSession;
    }

    @RequestMapping("{bookId}")
    public String listById(@PathVariable("bookId")
    Long bookId, Model model) {
        String returnPath = "message";

        try {
            Cookbook current = cookbookService.getCookBook(bookId);

            if (current != null) {
                if (current.isPrivate()
                        && userSession.getUser() != null
                        && userSession.getUser().getId() != current.getAuthor()
                                .getId()) {
                    model.addAttribute(
                            "errorMsgs",
                            Arrays.asList(new String[] { "Książka jest prywatna, a ty nie jesteś właścicielem." }));
                } else {
                    model.addAttribute("currentBook", current);
                    model.addAttribute("recipes",
                            cookbookService.getRecipesFromCookbook(current));

                    returnPath = "cookbook/show";
                }
            } else {
                model.addAttribute("errorMsgs",
                        Arrays.asList(new String[] { "Niepoprawna książka." }));
            }
        } catch (Exception ex) {
            log.info(String.format("Problem with recipe list. Exception: %s",
                    ex.getMessage()));

            model.addAttribute(
                    "errorMsgs",
                    Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));
        }

        return returnPath;
    }
}
